<template>
  <div class="check-record-container">
    <!-- 顶部标题 -->
    <div class="page-header">
      <h2 class="page-title">检查记录管理</h2>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <el-row :gutter="20" align="middle">
        <el-col :span="5">
          <el-input
              v-model="patientName"
              placeholder="患者姓名"
              clearable
              @clear="paging(1)"
              prefix-icon="Search">
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-input
              v-model="doctorName"
              placeholder="医师姓名"
              clearable
              @clear="paging(1)"
              prefix-icon="User">
          </el-input>
        </el-col>
        <el-col :span="10">
          <el-date-picker
              v-model="value"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="gai"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%">
          </el-date-picker>
        </el-col>
        <el-col :span="4" class="action-buttons">
          <el-button type="primary" @click="paging(1)" icon="Search">搜索</el-button>
          <el-button @click="resetSearch" icon="Refresh">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="openDialog" icon="Plus">添加检查记录</el-button>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table
          :data="page.list"
          style="width: 100%"
          stripe
          border
          v-loading="loading"
          height="calc(100vh - 320px)">

        <el-table-column
            prop="id"
            label="记录ID"
            width="120"
            align="center"
            sortable>
        </el-table-column>

        <el-table-column
            prop="name"
            label="检查名称"
            width="150"
            align="center">
        </el-table-column>

        <el-table-column
            prop="address"
            label="检查位置"
            width="180"
            align="center">
        </el-table-column>

        <el-table-column
            prop="rankRecord.patient.name"
            label="患者姓名"
            width="150"
            align="center">
        </el-table-column>

        <el-table-column
            prop="rankRecord.scheduling.doctor.name"
            label="医师姓名"
            width="150"
            align="center">
        </el-table-column>

        <el-table-column
            prop="resultDesc"
            label="结果描述"
            show-overflow-tooltip>
        </el-table-column>

        <el-table-column
            prop="resultContent"
            label="结果内容"
            width="180"
            show-overflow-tooltip>
        </el-table-column>

        <el-table-column
            label="结果图片"
            width="150"
            align="center">
          <template v-slot="scope">
            <el-image
                :src="scope.row.resultImage"
                :preview-src-list="[scope.row.resultImage]"
                style="width: 80px; height: 80px; border-radius: 4px;"
                fit="cover"
                hide-on-click-modal>
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>

        <el-table-column
            label="报告类型"
            width="120"
            align="center">
          <template v-slot="scope">
            <el-tag :type="scope.row.type == 1 ? 'success' : 'primary'" effect="light">
              {{ scope.row.type == 1 ? "检查报告" : "检验报告" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
            label="检查时间"
            width="180"
            align="center">
          <template v-slot="scope">
            <div class="time-cell">
              <el-icon><Clock /></el-icon>
              <span>{{ formatTime(scope.row.checkTime) }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="paging"
          :current-page="page.pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogFormVisible"
        @close="closed"
        width="600px"
        center>
      <el-form
          :model="form"
          :rules="formRule"
          ref="formRef"
          label-position="left"
          label-width="120px">

        <el-form-item label="检查名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入检查名称"></el-input>
        </el-form-item>

        <el-form-item label="检查位置" prop="address">
          <el-input v-model="form.address" placeholder="请输入检查位置"></el-input>
        </el-form-item>

        <el-form-item label="结果描述" prop="resultDesc">
          <el-input
              v-model="form.resultDesc"
              type="textarea"
              :rows="3"
              placeholder="请输入检查结果描述">
          </el-input>
        </el-form-item>

        <el-form-item label="结果内容" prop="resultContent">
          <el-input
              v-model="form.resultContent"
              type="textarea"
              :rows="3"
              placeholder="请输入检查结果内容">
          </el-input>
        </el-form-item>

        <el-form-item label="挂号号码" prop="rankId">
          <el-select
              v-model="form.rankId"
              placeholder="请选择挂号号码"
              style="width: 100%"
              filterable>
            <el-option
                v-for="item in rankRecordList"
                :key="item.id"
                :label="`${item.id} (${item.patient?.name || '未知患者'})`"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="报告类型" prop="type">
          <el-select
              v-model="form.type"
              placeholder="请选择报告类型"
              style="width: 100%">
            <el-option label="检查报告" value="1"></el-option>
            <el-option label="检验报告" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="上传图片">
          <el-upload
              class="upload-demo"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleSelFileChange">
            <el-button type="primary" icon="Upload">选择图片</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传检查结果图片，支持JPG/PNG格式
              </div>
            </template>
          </el-upload>
          <div class="image-preview" v-if="imgUrl">
            <el-image
                :src="imgUrl"
                style="width: 120px; height: 120px; margin-top: 10px;"
                fit="contain">
            </el-image>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogFormVisible = false" size="large">取消</el-button>
        <el-button type="primary" @click="submitForm" size="large">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import axios from "axios"
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, User, Plus, Refresh, Clock, Picture, Upload } from '@element-plus/icons-vue'

const dialogFormVisible = ref(false)
const form = ref({})
const formRef = ref()
const pageSize = ref(10)
const page = ref({})
const patientName = ref('')
const doctorName = ref('')
const value = ref('')
const startTime = ref('')
const endTime = ref('')
const file = ref()
const imgUrl = ref('')
const rankRecordList = ref([])
const loading = ref(false)
const dialogTitle = ref('添加检查记录')

const closed = () => {
  form.value = {}
  imgUrl.value = ''
  file.value = null
}

const handleSelFileChange = (f) => {
  file.value = f.raw
  imgUrl.value = URL.createObjectURL(f.raw)
}

const openDialog = () => {
  dialogTitle.value = '添加检查记录'
  dialogFormVisible.value = true
}

const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      add()
    }
  })
}

const add = () => {
  let formData = new FormData()
  formData.append("name", form.value.name)
  formData.append("address", form.value.address)
  formData.append("rankId", form.value.rankId)
  formData.append("resultDesc", form.value.resultDesc)
  formData.append("resultContent", form.value.resultContent)
  formData.append("type", form.value.type)
  if (file.value) {
    formData.append("file", file.value)
  }

  loading.value = true
  axios.post('check_record/add', formData)
      .then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg)
          dialogFormVisible.value = false
          paging(1)
        } else {
          ElMessage.error(res.data.msg)
        }
      })
      .catch(error => {
        ElMessage.error('操作失败')
        console.error(error)
      })
      .finally(() => {
        loading.value = false
      })
}

const paging = (curPage = 1) => {
  loading.value = true
  axios.get('check_record/getPNmaeDNameDate', {
    params: {
      pageNum: curPage,
      pageSize: pageSize.value,
      patientName: patientName.value,
      doctorName: doctorName.value,
      startTime: startTime.value,
      endTime: endTime.value
    }
  })
      .then(res => {
        page.value = res.data.data
        if (res.data.code == 200) {
          ElMessage.success(res.data.msg)
        } else {
          ElMessage.error(res.data.msg)
        }
      })
      .catch(error => {
        ElMessage.error('获取数据失败')
        console.error(error)
      })
      .finally(() => {
        loading.value = false
      })
}

const gai = () => {
  if (value.value && value.value.length === 2) {
    startTime.value = value.value[0]
    endTime.value = value.value[1]
  } else {
    startTime.value = ''
    endTime.value = ''
  }
}

const resetSearch = () => {
  patientName.value = ''
  doctorName.value = ''
  value.value = ''
  startTime.value = ''
  endTime.value = ''
  paging(1)
}

const handleSizeChange = (ps) => {
  pageSize.value = ps
  paging(1)
}

const getAllRankRecord = () => {
  axios.get('rankRecord/getAllRankRecord')
      .then(res => {
        if (res.data.code == 200) {
          rankRecordList.value = res.data.data
        } else {
          ElMessage.error(res.data.msg)
        }
      })
      .catch(error => {
        ElMessage.error('获取挂号记录失败')
        console.error(error)
      })
}

const formRule = {
  name: [
    { required: true, message: '请输入检查名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入检查位置', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  resultDesc: [
    { required: true, message: '请输入检查结果描述', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur' }
  ],
  resultContent: [
    { required: true, message: '请输入检查结果内容', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择检查类型', trigger: 'change' }
  ],
  rankId: [
    { required: true, message: '请选择挂号记录', trigger: 'change' }
  ]
}

onMounted(() => {
  getAllRankRecord()
  paging(1)
})
</script>

<style lang="scss" scoped>
.check-record-container {
  padding: 20px;
  background-color: #f8fafc;
  min-height: 100vh;

  .page-header {
    margin-bottom: 20px;

    .page-title {
      color: #303133;
      font-size: 20px;
      font-weight: 600;
      margin: 0;
      display: flex;
      align-items: center;

      &::before {
        content: "";
        display: inline-block;
        width: 4px;
        height: 16px;
        background-color: #409EFF;
        margin-right: 10px;
        border-radius: 2px;
      }
    }
  }

  .search-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #ebeef5;

    .action-buttons {
      display: flex;
      justify-content: flex-end;
    }
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .table-card {
    border-radius: 8px;
    border: 1px solid #ebeef5;
    margin-bottom: 20px;

    :deep(.el-table) {
      .time-cell {
        display: flex;
        align-items: center;
        justify-content: center;

        .el-icon {
          margin-right: 5px;
          color: #909399;
        }
      }

      .image-error {
        width: 80px;
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f7fa;
        color: #c0c4cc;
        border-radius: 4px;
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    padding: 20px 0;
  }

  .upload-demo {
    :deep(.el-upload) {
      text-align: left;
    }

    .el-upload__tip {
      margin-top: 5px;
      color: #909399;
      font-size: 12px;
    }
  }

  .image-preview {
    margin-top: 10px;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    padding: 5px;
    display: inline-block;
  }
}

:deep(.el-dialog) {
  border-radius: 8px;

  .el-dialog__header {
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;
  }

  .el-dialog__footer {
    border-top: 1px solid #ebeef5;
    padding: 20px;
  }
}
</style>